package com.zhangxiaofanfan.hotcode.second;

import java.util.HashSet;
import java.util.Set;

/**
 *
 *
 * @date 2024-06-29 03:21:25
 * @author zhangxiaofanfan
 */
public class HotCode068 {
    public static void main(String[] args) {
        HotCode068 hotCode = new HotCode068();
        int[] nums1 = {1, 3};
        int[] nums2 = {2, 4};
        System.out.println(hotCode.findMedianSortedArrays(nums1, nums2));
    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length == 0 && nums2.length == 0) {
            return 0;
        }
        Set<Integer> set = new HashSet<>();
        int sum = 0, count = 0, index = 0, index1 = 0, index2 = 0, min;
        if ((nums1.length + nums2.length) % 2 == 1) {
            set.add((nums1.length + nums2.length) / 2);
            count = 1;
        } else {
            set.add((nums1.length + nums2.length) / 2);
            set.add((nums1.length + nums2.length) / 2 - 1);
            count = 2;
        }
        while (!set.isEmpty()) {
            if (index1 >= nums1.length) {
                min = nums2[index2];
                index2++;
            } else if (index2 >= nums2.length) {
                min = nums1[index1];
                index1++;
            } else {
                if (nums1[index1] < nums2[index2]) {
                    min = nums1[index1];
                    index1++;
                } else {
                    min = nums2[index2];
                    index2++;
                }
            }
            if (set.contains(index)) {
                sum += min;
                set.remove(index);
            }
            index++;
        }
        return sum * 1.0 / count;
    }
}
